package com.lizicloud.infrastructure.common.utils;

/**
 * JSON工具类
 */
public class JsonUtils {
    
    /**
     * 对象转JSON字符串
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            return "null";
        }
        
        try {
            // 简单实现，实际项目中建议使用Jackson或Gson
            if (obj instanceof String) {
                return "\"" + escapeString((String) obj) + "\"";
            } else if (obj instanceof Number || obj instanceof Boolean) {
                return obj.toString();
            } else if (obj.getClass().isArray()) {
                return arrayToJson((Object[]) obj);
            } else {
                return objectToJson(obj);
            }
        } catch (Exception e) {
            throw new RuntimeException("对象转JSON失败", e);
        }
    }
    
    /**
     * JSON字符串转对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        if (json == null || json.isEmpty() || clazz == null) {
            return null;
        }
        
        try {
            // 简单实现，实际项目中建议使用Jackson或Gson
            if (json.equals("null")) {
                return null;
            } else if (clazz == String.class) {
                return clazz.cast(unescapeString(json.replace("\"", "")));
            } else if (Number.class.isAssignableFrom(clazz)) {
                return parseNumber(json, clazz);
            } else if (clazz == Boolean.class) {
                return clazz.cast(Boolean.parseBoolean(json));
            } else {
                return parseObject(json, clazz);
            }
        } catch (Exception e) {
            throw new RuntimeException("JSON转对象失败", e);
        }
    }
    
    /**
     * 格式化JSON字符串
     */
    public static String formatJson(String json) {
        if (json == null || json.isEmpty()) {
            return json;
        }
        
        StringBuilder formatted = new StringBuilder();
        int indentLevel = 0;
        boolean inQuotes = false;
        
        for (int i = 0; i < json.length(); i++) {
            char c = json.charAt(i);
            
            if (c == '"' && (i == 0 || json.charAt(i - 1) != '\\')) {
                inQuotes = !inQuotes;
            }
            
            if (!inQuotes) {
                switch (c) {
                    case '{':
                    case '[':
                        formatted.append(c).append("\n");
                        indentLevel++;
                        formatted.append(getIndent(indentLevel));
                        break;
                    case '}':
                    case ']':
                        formatted.append("\n");
                        indentLevel--;
                        formatted.append(getIndent(indentLevel));
                        formatted.append(c);
                        break;
                    case ',':
                        formatted.append(c).append("\n");
                        formatted.append(getIndent(indentLevel));
                        break;
                    case ':':
                        formatted.append(c).append(" ");
                        break;
                    default:
                        if (Character.isWhitespace(c)) {
                            break;
                        }
                        formatted.append(c);
                        break;
                }
            } else {
                formatted.append(c);
            }
        }
        
        return formatted.toString();
    }
    
    /**
     * 检查是否为有效的JSON字符串
     */
    public static boolean isValidJson(String json) {
        if (json == null || json.isEmpty()) {
            return false;
        }
        
        try {
            // 简单验证
            json = json.trim();
            return (json.startsWith("{") && json.endsWith("}")) || 
                   (json.startsWith("[") && json.endsWith("]")) ||
                   json.equals("null") ||
                   (json.startsWith("\"") && json.endsWith("\"")) ||
                   json.equals("true") || json.equals("false") ||
                   json.matches("-?\\d+(\\.\\d+)?");
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 获取JSON路径值
     */
    public static Object getJsonValue(String json, String path) {
        if (json == null || json.isEmpty() || path == null || path.isEmpty()) {
            return null;
        }
        
        try {
            // 简单实现，支持基本的路径访问
            String[] parts = path.split("\\.");
            String current = json;
            
            for (String part : parts) {
                if (part.contains("[")) {
                    // 数组访问
                    String arrayName = part.substring(0, part.indexOf("["));
                    String indexStr = part.substring(part.indexOf("[") + 1, part.indexOf("]"));
                    int index = Integer.parseInt(indexStr);
                    
                    current = extractArrayValue(current, arrayName, index);
                } else {
                    // 对象访问
                    current = extractObjectValue(current, part);
                }
                
                if (current == null) {
                    break;
                }
            }
            
            return current;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 对象转JSON（私有方法）
     */
    private static String objectToJson(Object obj) {
        StringBuilder json = new StringBuilder("{");
        
        try {
            java.lang.reflect.Field[] fields = obj.getClass().getDeclaredFields();
            boolean first = true;
            
            for (java.lang.reflect.Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(obj);
                
                if (!first) {
                    json.append(",");
                }
                first = false;
                
                json.append("\"").append(field.getName()).append("\":");
                json.append(toJson(value));
            }
            
            json.append("}");
            return json.toString();
        } catch (Exception e) {
            throw new RuntimeException("对象转JSON失败", e);
        }
    }
    
    /**
     * 数组转JSON（私有方法）
     */
    private static String arrayToJson(Object[] array) {
        StringBuilder json = new StringBuilder("[");
        
        for (int i = 0; i < array.length; i++) {
            if (i > 0) {
                json.append(",");
            }
            json.append(toJson(array[i]));
        }
        
        json.append("]");
        return json.toString();
    }
    
    /**
     * 字符串转义（私有方法）
     */
    private static String escapeString(String str) {
        if (str == null) {
            return "";
        }
        
        return str.replace("\\", "\\\\")
                 .replace("\"", "\\\"")
                 .replace("\n", "\\n")
                 .replace("\r", "\\r")
                 .replace("\t", "\\t");
    }
    
    /**
     * 字符串反转义（私有方法）
     */
    private static String unescapeString(String str) {
        if (str == null) {
            return "";
        }
        
        return str.replace("\\n", "\n")
                 .replace("\\r", "\r")
                 .replace("\\t", "\t")
                 .replace("\\\"", "\"")
                 .replace("\\\\", "\\");
    }
    
    /**
     * 解析数字（私有方法）
     */
    @SuppressWarnings("unchecked")
    private static <T> T parseNumber(String json, Class<T> clazz) {
        if (clazz == Integer.class) {
            return (T) Integer.valueOf(json);
        } else if (clazz == Long.class) {
            return (T) Long.valueOf(json);
        } else if (clazz == Double.class) {
            return (T) Double.valueOf(json);
        } else if (clazz == Float.class) {
            return (T) Float.valueOf(json);
        } else if (clazz == Short.class) {
            return (T) Short.valueOf(json);
        } else if (clazz == Byte.class) {
            return (T) Byte.valueOf(json);
        }
        return null;
    }
    
    /**
     * 解析对象（私有方法）
     */
    private static <T> T parseObject(String json, Class<T> clazz) {
        // 简单实现，实际项目中需要更复杂的解析
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("解析对象失败", e);
        }
    }
    
    /**
     * 提取对象值（私有方法）
     */
    private static String extractObjectValue(String json, String key) {
        // 简单实现
        String searchKey = "\"" + key + "\":";
        int start = json.indexOf(searchKey);
        if (start == -1) {
            return null;
        }
        
        start += searchKey.length();
        int end = findValueEnd(json, start);
        return json.substring(start, end).trim();
    }
    
    /**
     * 提取数组值（私有方法）
     */
    private static String extractArrayValue(String json, String arrayName, int index) {
        // 简单实现
        return null;
    }
    
    /**
     * 查找值结束位置（私有方法）
     */
    private static int findValueEnd(String json, int start) {
        int depth = 0;
        boolean inQuotes = false;
        
        for (int i = start; i < json.length(); i++) {
            char c = json.charAt(i);
            
            if (c == '"' && (i == 0 || json.charAt(i - 1) != '\\')) {
                inQuotes = !inQuotes;
            }
            
            if (!inQuotes) {
                if (c == '{' || c == '[') {
                    depth++;
                } else if (c == '}' || c == ']') {
                    depth--;
                } else if (depth == 0 && (c == ',' || c == '}')) {
                    return i;
                }
            }
        }
        
        return json.length();
    }
    
    /**
     * 获取缩进（私有方法）
     */
    private static String getIndent(int level) {
        StringBuilder indent = new StringBuilder();
        for (int i = 0; i < level; i++) {
            indent.append("  ");
        }
        return indent.toString();
    }
    
    private JsonUtils() {
        // 私有构造函数，防止实例化
    }
}